<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous">
    </script>
    <style>
        .block-content {
            display: flex;
            flex-wrap: wrap;
        }

        .goods-list {
            width: 25%;
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }

        .goods-block {
            width: 260px;
            padding: 0 30px;
        }

        .goods-img {
            width: 200px;
            height: 200px;
        }

        .foot {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .add-card {
            width: 30px;
            height: 30px;
        }

        .mt20 {
            margin-top: 20px;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Mall</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
<!--                <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>-->
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle"
                       data-toggle="dropdown"
                       role="button"
                       aria-haspopup="true"
                       aria-expanded="false">购物车 <span class="caret"></span></a>
                    <ul class="dropdown-menu" id="carts-list">

                    </ul>
                </li>

<!--                <li class="dropdown">-->
<!--                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>-->
<!--                    <ul class="dropdown-menu">-->
<!--                        <li><a href="#">Action</a></li>-->
<!--                        <li><a href="#">Another action</a></li>-->
<!--                        <li><a href="#">Something else here</a></li>-->
<!--                        <li role="separator" class="divider"></li>-->
<!--                        <li><a href="#">Separated link</a></li>-->
<!--                        <li role="separator" class="divider"></li>-->
<!--                        <li><a href="#">One more separated link</a></li>-->
<!--                    </ul>-->
<!--                </li>-->
            </ul>
            <form class="navbar-form navbar-left">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Search">
                </div>
                <button type="submit" class="btn btn-default">查询</button>
            </form>
            <ul class="nav navbar-nav navbar-right">
                <li style="text-align: center">
                    <a style="color: blue" id="display_username"></a>
                </li>
                <li class="dropdown">
                    <a href="#"
                       class="dropdown-toggle"
                       data-toggle="dropdown"
                       role="button"
                       aria-haspopup="true"
                       aria-expanded="false">系统功能 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#" data-toggle="modal" data-target="#loginModal">登录</a></li>
                        <li><a href="#" data-toggle="modal" data-target="#registerModal">注册</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#" onclick="logout()">退出登录</a></li>
                    </ul>
                </li>
            </ul>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>
<div class="container">
    <div class="block-content" id="blockData">
        <!-- 商品列表 -->
    </div>
</div>
<div class="modal-container">
    <!-- Modal -->
    <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="loginModalTitle">登录到你的账户</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="login_username" class="col-sm-2 control-label">账号</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="login_username" placeholder="请输入用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="login_password" class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10">
                                <input type="password" class="form-control" id="login_password" placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox"> 记住我
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="button" class="btn btn-default" onclick="login()">登录</button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<!--                    <button type="button" class="btn btn-primary">登录</button>-->
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">注册账户</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="reg_username" class="col-sm-2 control-label">账号</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="reg_username" placeholder="请输入用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="reg_password" class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10">
                                <input type="password" class="form-control" id="reg_password" placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="reg_password_again" class="col-sm-2 control-label">确认密码</label>
                            <div class="col-sm-10">
                                <input type="password" class="form-control" id="reg_password_again" placeholder="请再次输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox"> 记住我
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="button" class="btn btn-default" onclick="register()">注册</button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<!--                    <button type="button" class="btn btn-primary">注册</button>-->
                </div>
            </div>
        </div>

    </div>
</div>
</body>
</html>
<script>

    window.onload = function () {
        const userStorage = localStorage.getItem("user")
        const user = JSON.parse(userStorage)
        if (user === null) {
            document.getElementById("display_username").innerHTML = "请登录";
            return;
        }
        document.getElementById("display_username").innerHTML = "欢迎您，" + user.user.account;
        loadGoods();
    }
    function loadCart() {
        const user = localStorage.getItem("user");
        if (!user) {
            return;
        }
        const cart = JSON.parse(user).cart;
        if (cart.length === 0) {
            return;
        }
        const cid = user.id;
        $.ajax({
            url: `/car?cid=${cid}`,
            type: "GET",
            dataType: "text",
            success: function (data) {
                const res = JSON.parse(data);
                if (res.code !== 200) {
                    alert(res.msg);
                    return;
                }
                const cartList = res.data;
                cartList.forEach(item => {
                    renderCartItem(item);
                })
            }
        })
    }
    function loadGoods() {
        const user = localStorage.getItem("user");
        if (!user) {
            alert("请先登录");
            return;
        }
        $.ajax({
            url: "loadGoods",
            type: "GET",
            dataType: "text",
            success: function (data) {
                const res = JSON.parse(data);
                if (res.code !== 200){
                    alert(res.msg);
                    return;
                }
                const goodsList = res.data;
                goodsList.forEach(item => {renderGoodsItem(item);})
            }
        });
    }
    function renderCartItem(item){
        // TODO 渲染购物车中的商品
    }
    function renderGoodsItem(item){
        $(`<div class="goods-list">
            <div class="goods-block">
                <img src="${item.img}"
                     alt="" class="goods-img">
                <div class="foot mt20">
                    <div class="goods-name">${item.title}</div>
                    <img src="./icon/cart.png"
                         alt="" class="add-card" onclick="addCart(${item.id},'${item.title}',${item.price})">
                </div>
                <div class="foot mt20">
                    <div class="new-price" style="color: orange; font-size:18px; font-weight: bold;">

                        ${(item.price * 0.85).toFixed(2)}元</div>
                    <div class="old-price" style="font-size:14px; text-decoration: line-through; color: #999;">${item.price}元</div>
                </div>
            </div>
        </div>`).appendTo("#blockData")
    }
    function addCart(id,title,price){
        const userStorage = localStorage.getItem("user");
        if (!userStorage){
            alert("请先登录");
            return;
        }
        const user = JSON.parse(userStorage);
        const carts = user.carts;

        if (carts.some(cart => cart.gid == id)){
            alert("商品已在购物车中");
            return;
        }
        carts.push({gid: id, title: title, price: (price * 0.85).toFixed(2)})
        $.ajax({
            url: "/cart",
            type: "POST",
            data: {
                action:"add",
                gid: id,
                title: title,
                price: (price * 0.85).toFixed(2),
                cid: user.user.id,
            },
            dataType: "text",
            success: function (data) {
                if (data !== 'Y'){
                    alert("添加失败,请重试");
                    return;
                }
                alert("添加成功");
            }
        })

        localStorage.setItem("user", JSON.stringify(user));
    }
    function login(){
        const username = document.getElementById("login_username").value;
        const password = document.getElementById("login_password").value;
        $.ajax({
            url: "/consumer-login",
            type: "POST",
            data: {username: username, password: password},
            dataType: "text",
            success: function (data) {
                const res = JSON.parse(data);
                if (res.code !== 200){
                    alert(res.msg);
                    return;
                }
                localStorage.setItem("user", JSON.stringify(res.data));
                $('#loginModal').modal('hide');
                window.location.reload();

            }
        })
    }
    function register(){
        const username = document.getElementById("reg_username").value;
        const password = document.getElementById("reg_password").value;
        const password_again = document.getElementById("reg_password_again").value;
        if (password === "" || password_again === "") {
            alert("密码不能为空");
            return;
        }
        if (password !== password_again){
            alert("两次输入的密码不一致");
            return;
        }
        console.log("register",username, password)
        $.ajax({
            url: "/consumer-register",
            type: "POST",
            data: {username: username, password: password},
            dataType: "text",
            success: function (data) {
                console.log(data)
                const res = JSON.parse(data);
                if (res.code !== 200){
                    alert(res.msg);
                    return;
                }
                $('#registerModal').modal('hide');
                alert("注册成功，请登录");
            }
        });
    }
    function verify(){
        const userStorage = localStorage.getItem("user");
        const user = JSON.parse(userStorage)
        if ( user === null){
            document.getElementById("display_username").innerHTML = "请登录";
            alert("请登录");
            return;
        }
        document.getElementById("display_username").innerHTML = "欢迎您，" + user.account;
    }
    function logout() {
        const ans = window.confirm("确认退出?");
        // TODO 退出系统
        if (ans) {
            $.ajax({
                url: "/consumer-logout",
                type: "POST",
                dataType: "text",
                success: function (data) {
                    localStorage.removeItem("user");
                    document.getElementById("display_username").innerHTML = "请登录";
                    window.location.reload();
                }
            });
        }
    }
</script>